#include <QtGui/QApplication>
#include <QTextCodec>
#include <QString>
#include <QRegExp>

#include "mainwindow.h"
#include "textrun.h"
#include "helper.h"

int main(int argc, char *argv[])
{
    QTextCodec *codec = QTextCodec::codecForName("utf8");
    QTextCodec::setCodecForTr(codec);
    QTextStream errout(stderr);
    QTextStream cout(stdout);

    QString progName = "GNU SOSATOR";
	QString progVersion = "0.3 BETA";

    Helper helper(progName, progVersion);

    QRegExp urlValidator("^http://[a-z0-9-\\./]+", Qt::CaseInsensitive);
    QRegExp helpValidator("-{1,2}h(elp)?$", Qt::CaseInsensitive);
    bool textMode = false;
    bool pb_mode = false; // draw text progress bar
	bool falos = false; // прогрессбар в виде хуя
    QString *url = 0;

    if (argc > 1)
    {
        for (int i = 1; i < argc; ++i)
        {
            QString param(argv[i]);
            if (helpValidator.exactMatch(param))
            {
                helper.showUsage();
                return EXIT_SUCCESS;
            }
            else if (param == "-v" || param == "--version")
            {
                helper.showVersion();
                return EXIT_SUCCESS;
            }
            else if ( param == "-t" )
            {
                textMode = true;
            }
            else if ( (param == "-tp") || (param == "-pt") )
            {
                textMode = true;
                pb_mode  = true;
            }
			else if ( (param == "-tpf") || (param == "-ptf") )
			{
				textMode = true;
				pb_mode  = true;
				falos = true;
			}
            else if (url == 0 && urlValidator.exactMatch(param))
            {
                url = new QString(param);
            }
            else
            {
                helper.wrongParametr(param);
                return EXIT_FAILURE;
            }
        }
    }

    QApplication a(argc, argv, !textMode);
        a.setApplicationName(progName);
        a.setApplicationVersion(progVersion);
    
    if (!textMode)
    {
        MainWindow w(0, url);
        w.show();
        return a.exec();
    } else if (url != 0)
    {
        TextRun trun(url);
		trun.setPbMode( pb_mode, falos );
        trun.Go();
        QObject::connect(&trun, SIGNAL(done()), &a, SLOT(quit()));
        return a.exec();
    } else
    {
        return EXIT_FAILURE;
    }

}
